#include <stdlib.h>
#include <stdio.h>
#include <math.h>

long int MAX_TIME             = 10000L;
long int NO_STATIONS          = 100L;
long int FRAME_LENGTH         = 100L;
long int  medium_occupied_till = -1;
long int  survival_timer       = -1;
long int  successful_packets   = 0;
long int  no_frames          ;  
long int temp_abs;
long TOTAL_NO_RUNS        = 10000;
int station_id[1000];

void TriggerSend(int current_time)
{

if(current_time < medium_occupied_till) {
//if medium is still occupied, collision has occurred
    survival_timer = -1;
  }   else survival_timer = 0;
//set medium to be occupied for  FRAME_LENGTH;
 medium_occupied_till = current_time + FRAME_LENGTH;
}


int main()
{
int i,arrival_rate,time,station_index;
no_frames          = MAX_TIME / FRAME_LENGTH;
//aloha protocol simulation
for(i = 0;i < NO_STATIONS; i++)
station_id[i]=1; //activate all stations

//simulating for various arrival rate
for(arrival_rate = 0; arrival_rate < TOTAL_NO_RUNS/(NO_STATIONS/4); arrival_rate ++) 
{

medium_occupied_till = -1;
survival_timer       = -1;
successful_packets   = 0;
	for(time = 0; time < MAX_TIME; time++) 
	{
		for(station_index = 0; station_index < NO_STATIONS; station_index++)	
			{  temp_abs=(abs(rand()) % (TOTAL_NO_RUNS));
//(abs(rand())%(100*NO_STATIONS*FRAME_LENGTH));
				if( temp_abs< arrival_rate)
				{station_id[station_index]=1;
				TriggerSend(time);}
                              //printf("temp_abs %d medium_occupied_till%d survival_timer %d arrival_rate %d\n",temp_abs,medium_occupied_till,survival_timer,arrival_rate);
			}//for station_index

		if(survival_timer != -1) survival_timer++;
		if(survival_timer == FRAME_LENGTH) 
			{
			successful_packets++;
			survival_timer = -1;
			}
	}//for time <MAX_TIME

printf(" arrival rate  %d success rate %d\n",arrival_rate/100,successful_packets/no_frames);
}//for arrival_rate


}


